from datetime import datetime
import json
from django.views.decorators.http import require_POST, require_GET
from django.views.decorators.csrf import csrf_exempt
from tanxi.client.Handler.JsonResponse import create_response
from tanxi.client.Handler.Logger import log_error, log_info
from django.conf import settings

# 数据库 选择
if settings.DATABASE_TYPE == 'mysql':
    from tanxi.client.utils.mysql.articles_mysql import ArticleUpdateHandler, ArticleQueryHandler

elif settings.DATABASE_TYPE == 'sqlite':
    from tanxi.client.utils.sqlite.articles_sqlite import ArticleUpdateHandler, ArticleQueryHandler 
else:
    raise ValueError("Unsupported database type specified in settings.")

# 全局异常处理 --> 中间件 ExceptionHandler 做了

# 类功能初始化
# 查询
query = ArticleQueryHandler()
# 增删改
update = ArticleUpdateHandler()

@require_GET
@csrf_exempt
def get_articles(request):
    # 文章查询
    id = request.GET.get('id')
    title = request.GET.get('title')
    author_id = request.GET.get('author_id')
    is_published = request.GET.get('is_published')
    # 按参数查询
    if id or title or author_id or is_published:

        articles = query.query_articles(id, title, author_id, is_published)
        
        articles = list(articles.values())
        log_info(f"按参数查询结果: {articles}")

    # 查询所有文章
    else:
        articles = query.query_articles()
        articles = list(articles.values())
        log_info(f"查询所有文章结果: {articles}")
    
    return create_response(code=200, message="Success", remarks="查询成功", data=articles)


# 文章 增改
@require_POST
@csrf_exempt
def write_articles(request):
    # 解析请求体
    try:
        data = json.loads(request.body)
        log_info(data)  # 假设 log_info 是一个日志记录函数

        # 从数据中提取字段
        article_id = data.get('id')
        title = data.get('title')
        content = data.get('content')
        publish_time = data.get('publish_time')
        is_published = data.get('is_published', False)  # 默认为 False
        author_id = data.get('author_id')
        read_count = data.get('read_count', 0)  # 默认为 0
        tags = data.get('tags', [])  # 默认为空列表
        updated_time = data.get('updated_time')

        # 如果 publish_time 和 updated_time 未提供，则使用当前时间
        if not publish_time:
            publish_time = datetime.now().isoformat()
        if not updated_time:
            updated_time = datetime.now().isoformat()

        # 构造文章数据
        article_data = {
            'title': title,
            'content': content,
            'publish_time': publish_time,
            'is_published': is_published,
            'author_id': author_id,
            'read_count': read_count,
            'tags': tags,
            'updated_time': updated_time
        }
        # 仅在 article_id 明确存在且非空时添加
        log_info(f"文章id {article_id}")
        if article_id is not None and article_id != '':
            article_data['id'] = article_id
        # 调用 ArticleUpdateHandler 写入或更新文章
        result = ArticleUpdateHandler().update_or_create_article(article_data)

        # 返回成功响应
        return create_response(code=200, message="Success", remarks="写入成功", data=result)

    except json.JSONDecodeError:
        return create_response(code=400, message="Error", remarks="请求体不是有效的 JSON 格式", data=None)

# 文章 删除
@require_POST
@csrf_exempt
def delete_articles(request):
    data = json.loads(request.body)
    article_id = data.get('article_id')
    info = ArticleUpdateHandler().delete_article(article_id)
    
    if info:
        return create_response(code=200, message="Success", remarks="删除成功", data=[])
    else:
        return create_response(code=400, message="Error", remarks="删除失败", data='该文章不存在')

